import { getinputData } from '../data/cwbbvk.js';
import { fillInputDone, isFillYearBeforeLast } from '../../common.js';

function fillinputCwbb({ saasData, baseInfo }, sheet) {
  let isYearReport = saasData.isYearReport;
  let ins = saasData.data.openParams.taxInfo.institution === '2013' ? 'xqykjzz' : 'qykjzz';
  let inputData;
  if (isYearReport) {
    inputData = saasData.data.openParams.inputData.data[sheet];
    let lastYearData = saasData.data.openParams.inputData.lastYearData[sheet];
    if (sheet === 'profit' || sheet === 'cash') {
      inputData = inputData.map((item, index) => {
        let obj = {};
        obj.colValue1 = ins === 'qykjzz' ? item.colValue3 : item.colValue1;
        obj.colValue2 = ins === 'qykjzz' ? lastYearData[index].colValue3 : lastYearData[index].colValue1;
        obj.reportItemName = lastYearData[index].reportItemName;
        return obj;
      });
    }
  } else {
    inputData = saasData.data.openParams.inputData.data[sheet];
  }
  if (['balance', 'profit', 'cash'].includes(sheet)) {
    try {
      let data = getinputData(inputData, ins, sheet, isYearReport);
      let contentIframe = document.querySelector('#allframe > div > div.x-tab-panel-body > iframe').contentDocument;
      let divs = contentIframe.querySelectorAll('body > div');
      let currentDivs = Array.from(divs).find(item => item.id.includes('table') && item.style.display !== 'none');
      let iframe = currentDivs.querySelector('iframe').contentDocument;
      console.log(data);
      
      let fillYearBeforeLast = isFillYearBeforeLast(baseInfo);
      console.log(fillYearBeforeLast);
      data.forEach(({ key, value = 0 }) => {
        if(!fillYearBeforeLast && isYearReport && key.includes('l3')) {
          return;
        }
        let input = iframe.querySelector(`#${key}`);
        input.set('value', value || 0)
          .set('realvalue', value || 0)
          .fireEvent('change');
      });
      fillInputDone({
        tax: 'cwbb', // 税种
        success: true, // 是否成功
        message: "财务报表-填报成功", // 文案
      })
    } catch (e) {
      console.log(e);
      fillInputDone({
        tax: 'cwbb', // 税种
        success: false, // 是否成功
        message: "财务报表-填报失败，请联系技术人员", // 文案
      })
    }
  }
}


export { fillinputCwbb }